import { ref, type Ref, onMounted } from 'vue'
import type { IAccount, IRole } from '@/utils/types'
import {
    RequestAccountList,
    RequestRoleList,
    RequestManagerDelete,
} from '@/api/index'
import { baseURL } from '@/utils/request'
/**
 * 账户
 */
export const useAccount = () => {
    // 账户列表
    const acountList: Ref<Array<IAccount>> = ref([])
    const roleList: Ref<Array<IRole>> = ref([])
    const disableAccountAdd: Ref<boolean> = ref(false)
    onMounted(() => {
        getRoleList()
        getAccountList()
    })

    /**
     * 获取账户列表
     */
    const getAccountList = async () => {
        const data = await RequestAccountList()
        const { resultCode, resultInfo } = data
        if (resultCode === 1) {
            acountList.value = resultInfo
        }
    }
    /**
     * 角色列表
     */
    const getRoleList = async () => {
        const data = await RequestRoleList()
        const { resultCode, resultInfo } = data
        if (resultCode === 1) {
            roleList.value = resultInfo.roles
        }
    }
    /**
     * 过滤url地址
     */
    const onFilterUrl = (url: string) => {
        if (url) {
            if (url.indexOf('http') !== -1) {
                return url
            } else {
                return baseURL + url
            }
        }
    }
    /**
     * 角色名称
     */
    const getRoleName = (roleId: number) => {
        const list = roleList.value
        const role = list.find(item => item.r_id === roleId)
        return role?.rolename
    }

    /**
     * 添加账户
     */
    const bindAccountAdd = () => {
        disableAccountAdd.value = true
    }
    /**
     * 删除账户
     * @param id 
     */
    const bindAccountDelete = async (id: number) => {
        const data = await RequestManagerDelete(id)
        const { resultCode } = data
        if (resultCode === 1) {
            getAccountList()
        }
       
    }
    /**
     * 刷新
     */
    const bindRefresh = ()=>{
        getAccountList()
    }

    /**
     * 关闭
     */
    const closeDialog = ()=>{
        disableAccountAdd.value = false
        getAccountList()
    }
    return {
        acountList,
        disableAccountAdd,
        onFilterUrl,
        getRoleName,
        bindAccountAdd,
        bindAccountDelete,
        bindRefresh,
        closeDialog
    }
}
